﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;

using Mvc.XForms.Examples.Model;
using Mvc.XForms.Examples.Repository;
using Mvc.XForms.Utilities;

namespace Mvc.XForms.Examples.Validation {
	public class CustomerValidator {
		private Customer customer;
		private ModelStateDictionary modelState;
		private IRepository<Customer> customerRepository;

		public CustomerValidator(Customer customer, ModelStateDictionary modelState, IRepository<Customer> customerRepository) {
			this.customer = customer;
			this.modelState = modelState;
			this.customerRepository = customerRepository;
		}

		public bool Validate() {
			var validator = new ModelValidator<Customer>(customer, modelState);

			validator.String(
				c => c.Name,
				name => string.IsNullOrEmpty(name),
				"Please enter a name"
			);

			validator.String(
				c => c.Name,
				name => customerRepository
					.AsQueryable()
					.Where(c => c.ID != customer.ID)
					.Any(c => c.Name.ToLowerInvariant() == customer.Name.ToLowerInvariant()),
				"Customer already exists"
			);

			return modelState.IsValid;
		}
	}
}
